<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\Dashboard;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;

use Encore\Admin\Grid;
use Encore\Admin\Form;
use App\Models\PlayerDataCommand;
use App\Models\CdkeyRef;


use App\Admin\Extra\Search\Html;
use \Illuminate\Support\Facades\Input;

use App\Models\Area;
use App\Models\GameConfigData;
use Redirect;

class CommandController extends Controller
{
    public function index()
    {
        $use_data['area_all'] = Area::areaSelectData(0);
        $use_data['area_online'] = Area::areaSelectData();
        
        return Admin::content(function (Content $content)use($use_data) {
            $pid = Input::get('pid');
            $area = Input::get('area', 0);
            $content->header('game command list [' . $pid . ']');
           
            
            $param = ['area' => $area, 'pid' => $pid];
            $content->row(Html::append([
                $area ?Html::button('Open GM', \App\Service\Common::build_url_query('/admin/command/open-gm-command',  $param), 'btn-goto-ajax btn-warning'):'',
            //     Html::likeRedirect('title', 'notice title', url()->current()),
            //     Html::button('GO', url()->current(), 'search-filter'),
                Html::sjs(url()->current()),
            ]));	

            $content->row($form_raw);
            $use_data['param'] = $param;
			$grid = Admin::grid(PlayerDataCommand::class, function(Grid $grid) use($use_data){
                $grid->model()->where('deleted_at', 0);

                $grid->actions(function($actions)use(&$row){
                    $row = $actions->row;
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $actions->append(Html::button('EDIT', '/admin/command/edit?id='.$actions->getKey(), 'btn-goto btn-xs'));
                    $actions->append(Html::button('DEL', '/admin/command/api-save?_id='.$actions->getKey().'&deleted_at=1', 'btn-goto btn-danger btn-xs btn-clear'));
                });

			    // 第一列显示id字段，并将这一列设置为可排序列
			    $grid->id('ID')->sortable();
                $grid->model()->orderBy('id', 'DESC');
                $grid->command('command');
                $grid->desc('command desc');
                

                $grid->send_time("send gm command")->display(function($value){
                    if ($value > 0) {
                        return date("Y-m-d H:i:s",$value);
                    }
                    $param_send = $use_data['param'];
                    $param_send['command'] = $this->command;
                    $param_send['status'] = 1;
                    return Html::button('send', \App\Service\Common::build_url_query('/admin/command/command', $param_send), 'btn-goto btn-xs btn-info');
                });


            });
        
            $content->row($grid->render());

        });       
    }
    public function anyArea()
    {
        return Admin::content(function (Content $content) {
            $content->header('server list');
            $content->row(Html::append([
                Html::likeRedirect('name', 'server name', url()->current()),
                Html::button('GO', url()->current(), 'search-filter'),
                Html::sjs(url()->current()),
            ]));

            $grid = Admin::grid(Area::class, function(Grid $grid){
                //$grid->model()->where('deleted_at', 0);//

                $grid->actions(function($actions)use(&$row){
                    $row = $actions->row;
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $actions->append(Html::button('edit extend', '/admin/area/edit-extend?id='.$row->id, 'btn-goto btn-xs'));
                });

                // 第一列显示id字段，并将这一列设置为可排序列
                $grid->model()->orderBy('id', 'DESC');
                $grid->name('area name');
                $grid->areaId('server area');
                $grid->data_table_update('data_table_update')->display(function(){
                    return "<a href=\"/admin/command/reload-config-list?area={$this->areaId}\">data table update</a>";
                });
                $grid->open_gm_command('open_gm_command')->display(function(){
                    return Html::button('open gm command', '/admin/command/open-gm-command?area='.$this->areaId, 'btn-goto-ajax btn-xs btn-info');

                });

                $grid->chat_gm('chat_gm')->display(function(){
                    return Html::button('Chat GM', '/admin/command/chat-gm?area='.$this->areaId, 'btn-goto btn-xs btn-info');

                });
                $grid->game_label('GameLabel')->display(function(){
                    return Html::button('GameLabel', '/admin/version/label-list?area='.$this->areaId, 'btn-goto btn-xs btn-info');
                });

                $grid->sync_player('SyncPlayers')->display(function(){
                    return Html::button('SyncPlayers', '/admin/command/sync-players?area='.$this->areaId, 'confirm-ajax btn-xs btn-warning');
                });

                $grid->state()->display(function($value){
                    switch ($value){
                    case 0:
                        $label_class = "label-default";
                        break;
                    case 1:
                        $label_class = "label-success";
                        break;
                    case -1:
                        $label_class = "label-danger";
                        break;
                    case 2:
                        $label_class = "label-info";
                        break;
                    }
                    $h = '<span id="'.$value.'" class="label '.$label_class.'">'.Area::$area_state_type[$value].'</span>';
                    return $h;
                });

                // 服务当前状态
                // $states = [
                //     'on'  => ['value' => 1, 'text' => 'online', 'color' => 'success'],
                //     'off' => ['value' => 0, 'text' => 'down', 'color' => 'default'],
                //     'url' => url()->to("/admin/area/api-send?_id={$row->id}"),
                // ];

                
                // 设置临时跳转路径 行操作使用 TODO
                //$grid->tmpUrl = url()->to("/admin/game-db-conf/api-save?id=".$grid->getKey()->value()."&status=".(''?0:1));
                // $tmp = $grid->state('server state')->switch($states)->display(function($value){
                //     $this->tmpUrl = url()->to("/admin/mail/api-send?_id=".$this->id."&state=".($value?0:1));
                //     return $value;
                // });

                $grid->filter(function ($filter) {

                    // 模糊查询 注意
                    //$filter->where(function($query){
                    //    //$aids = \App\Models\EMail::getAccountByName('', 'playerName');
                    //    //var_dump($aids);exit;
                    //    $query->where('title', 'like', 'T%');
                    //}, '邮件标题', 'title');

                    $filter->like('name', 'area name')->placeholder('');
                    

                    //$filter->disableIdFilter();
                });
                $grid->disableCreateButton();
                //$grid->disableExport();
                $grid->disableActions();
                $grid->disableRowSelector();
            });
        
            $content->row($grid->render());

        });
    }

    public function anyEdit(){
        $id = Input::get('id');

        $one = PlayerDataCommand::find($id) ?: new PlayerDataCommand;

        $data['one'] = $one;

        \Log::debug("command player ",[Area::areaSelectData(), intval($one->area_list)]);
        return Admin::content(function($content) use($data){
		    $content->header('player command edit');
            $grid = Admin::Form(PlayerDataCommand::class, function(Form $form)use($data){
                $one = $data['one'];
                //$one->area_list = explode(',', $one->area_list);

                $form->text('command', 'command')->default($one->command);
                $form->text('desc', 'desc')->default($one->desc);
               
                $form->hidden('_id', 'id')->default($one->id);
                $form->saved(function (Form $form) {
                    \Log::debug(json_encode(['data'=>'save click']));
                    admin_toastr('laravel-admin 提示','success');
                    return response('success');
                });
                $form->disablePjax();
                $form->setAction('/admin/command/api-save/');

            });
            $content->row($grid);
        });

    }

    public function anyCommand()
    {
        $use_data = Input::all();
        return Admin::content(function($content) use($use_data){
		    $content->header('player command edit');
            $grid = Admin::Form(PlayerDataCommand::class, function(Form $form)use($use_data){
                $one = $data['one'];
                //$one->area_list = explode(',', $one->area_list);

                $form->select('area', 'area')->options(Area::areaSelectData())->default($use_data['area']);
                $form->text('player_id', 'player id')->default(Input::get('pid'));
                $form->select('command', 'command')->options(PlayerDataCommand::listAll())->default($use_data['command']);
                $form->text('dataId', 'dataId')->default(Input::get('dataId'));
                $form->text('dataCnt', 'dataCnt')->default(Input::get('dataCnt'));
               
                $form->hidden('_id', 'id')->default($one->id);
                $form->saved(function (Form $form) {
                    \Log::debug(json_encode(['data'=>'save click']));
                    admin_toastr('laravel-admin 提示','success');
                    return response('success');
                });
                $form->disablePjax();
                $form->setAction('/admin/command/api-send/');

            });
            $content->row($grid);
        });
    }

    public function anyAdd()
    {
        return $this->anyEdit();
    }

    public function anyApiSave(){
        $data = Input::all();

        $url = url()->to("/admin/command");
        \Log::debug(json_encode(['data'=>$data, 'url' =>$url]));
        $one = PlayerDataCommand::find($data['_id']) ? : new PlayerDataCommand();

        PlayerDataCommand::assignByOut($one, $data);
        
        if (!$one->command || !$one->desc) {
            echo json_encode(['code' => 444, 'msg' => admin_toastr('command save data is empty!','error'), 'data' => $data]);
            return;
        }
        $one->save();
        
        echo json_encode(['code' => 0, 'msg' => admin_toastr('command save!','success'), 'data' =>$one]);
        return;
    }

    public function anyApiSend(){
        $data = Input::all();

        \Log::debug('send command begin', [json_encode($data)]);
        if (!$data['command'] || !$data['player_id']|| !$data['area']){
            admin_toastr('send command error!','error');
            
            echo json_encode(['code' => -444,'status'=>true, 'msg' => admin_toastr('send command error','error'), 'data' =>$data]);
            return;
        }

        \Log::debug("send command end", [$one]);
        // 发送邮件
        PlayerDataCommand::send($data);
        echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('send command success','success'), 'data' =>$data]);
    }

    public function anyReloadConfigList(){
        $req = Input::all();
        return Admin::content(function (Content $content)use($req) {
            $content->header('server config data table');
            $content->row(Html::append([
                Html::likeRedirect('name', 'config data table', url()->current()),
                Html::button('GO', url()->current(), 'search-filter'),
                Html::sjs(url()->current()),
            ]));

            $grid = Admin::grid(GameConfigData::class, function(Grid $grid)use($req){
                $grid->model()->orderBy('id', 'DESC');
                $grid->name('name');
                $grid->real_name('real name');
                

                // $grid->send_time("send gm command")->display(function($value){
                //     if ($value > 0) {
                //         return date("Y-m-d H:i:s",$value);
                //     }
                //     return Html::button('send', '/admin/command/command?command='.$this->command.'&status='.'1', 'btn-goto btn-xs btn-info');
                // });

                $grid->disableCreateButton();
                $grid->disableExport();
                $grid->actions(function($actions) use($req){
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->append(Html::button('sync', "/admin/command/reload-config?area={$req['area']}&id=".$actions->getKey(), 'btn-goto-ajax btn-xs'));
                });
                $grid->tools(function ($tools) {
                    $tools->batch(function ($batch) {
                        $batch->disableDelete();
                        // $batch->add('发布文章', '<a href ="">批量发送</a>');
                    });
                });
            });

            $content->row($grid->render());
        });
    }
    public function reloadConfCommand(){
        $req = Input::all();
        PlayerDataCommand::sendReloadConfig([$req["id"] ], $req['area']?:66);
        echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('send command success','success'), 'data' =>[]]);
    }

    // open gm command
    public function anyOpenGmCommand(){
        $req = Input::all();
        PlayerDataCommand::sendOpenGmCommand($req['area']?:1);

        echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('send command success','success'), 'data' =>[]]);
    }

    // gm 后台监控游戏聊天
    public function anyChatGM() {
        \Admin::js('/js/chat.js');
        return Admin::content(function (Content $content)use($req) {
        });
              
    }

    public function anySyncPlayerRoles() {
        $area = Input::get('area');
        $ret = \App\Models\Account\PlayerRole::syncPlayFromGame($area);
        $code = $ret ? 0: -444;
        echo json_encode(['code' => $code,'status'=>$ret, 'msg' => admin_toastr('send command success','success'), 'data' =>[]]);
    }
}
